#!/usr/bin/python3

import configparser
import optparse
import os.path
import os

import classes.fetchers.market as fetchers
import classes.storages as storages
import classes.connects as connects

if __name__ == '__main__':

    config_parser = configparser.SafeConfigParser()
    config_parser.read(os.path.join(os.path.dirname(__file__), 'config.ini'))

    option_parser = optparse.OptionParser()
    option_parser.add_option("--storage-host", type="str", dest="storage_host", default = config_parser.get('storage', 'host'), help="")
    option_parser.add_option("--storage-port", type="int", dest="storage_port", default = config_parser.get('storage', 'port'), help="")
    option_parser.add_option("--storage-user", type="str", dest="storage_user", default = config_parser.get('storage', 'user'), help="")
    option_parser.add_option("--storage-pass", type="str", dest="storage_pass", default = config_parser.get('storage', 'pass'), help="")
    option_parser.add_option("--storage-base", type="str", dest="storage_base", default = config_parser.get('storage', 'base'), help="")
    option_parser.add_option("--path-ingames", type="str", dest="path_ingames", default = config_parser.get('path', 'ingames'), help="")
    option_parser.add_option("--path-archive", type="str", dest="path_archive", default = config_parser.get('path', 'archive'), help="")
    option_parser.add_option("--path-exports", type="str", dest="path_exports", default = config_parser.get('path', 'exports'), help="")
    (options, params) = option_parser.parse_args()

    db = connects.Db(**options.__dict__)

    market = storages.Market(db)

    filedir = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.expandvars(os.path.expanduser(options.path_exports))))
    archive = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.expandvars(os.path.expanduser(options.path_archive))))
    for root, dirs, files in os.walk(filedir):
        dirs[:] = [] # do not recurse
        total = len(files)
        current = 0
        for file in files:
            filepath = os.path.join(root, file)
            current = current + 1
            print("Importing market log %d/%d: %s" % (current, total, filepath));
            try:
                db.start()
                fetcher = fetchers.Market(filepath = filepath)
                market.fulfil(fetcher)
                db.commit()
                os.rename(filepath, os.path.join(archive, file))
            except db.UniqueError:
                print("  DUPLICATE IGORED")
                db.rollback() # just ignore duplicated files, but do not fail. @todo: report on stdout
            except Exception as exception:
                db.rollback()
                raise exception

    print("Analyzing...")
    market.analyze()

    print("Done!")
